package org.jjj.org.service.impl;

import org.jjj.org.basic.service.impl.BaseServiceImpl;
import org.jjj.org.domain.Department;
import org.jjj.org.mapper.DepartmentMapper;
import org.jjj.org.service.IDepartmentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

@Service
//这里必须先继承再实现
public class DepartmentServiceImpl extends BaseServiceImpl<Department> implements IDepartmentService {
    @Autowired
    private DepartmentMapper departmentMapper;
    /**
     * 对于创建时间应该在后端自动生成
     * 后端来拼接path
     * @param department
     */
    @Override
    public void add(Department department) {
        department.setCreate_time(new Date());
        //先新增返回自增的id
        super.add(department);
        //新增时拼接path:父部门的path+/自己的id
        //如果没有选择父部门，path就是/自己的id
        Long id = department.getId();
        String path = "";
        //当前端不选父部门的时候自己就是顶级部门，这时候判断应该判断id是否为空，因为前端parent
        if (department.getParent().getId()==null){
            path = "/"+id;
        }else {
            //父部门不为空的话path:祖先级id(父部门的path)+自己的id
            Department parent = departmentMapper.selectById(department.getParent().getId());
            path =parent.getPath()+"/"+id;
        }
        //需要将拼接好的path重新给department对象
        department.setPath(path);
        //然后重置之后再修改一下后台数据库
        super.update(department);
    }

    @Override
    public void update(Department department) {
        department.setUpdate_time(new Date());
        //对于修改来说id已经存在了
        Long id = department.getId();
        String path = "";
        if (department.getParent().getId()==null){
            path = "/"+id;
        }else {
            //父部门不为空的话path:祖先级id(父部门的path)+自己的id
            Department parent = departmentMapper.selectById(department.getParent().getId());
            path =parent.getPath()+"/"+id;
        }
        //需要将拼接好的path重新给department对象
        department.setPath(path);
        super.update(department);
    }

    /**
     * 获取部门树
     * @return
     */
    @Override
    public List<Department> getDeptTree() {
        return departmentMapper.getDeptTree();

    }
}
